package com.jack.tang.juc.demos;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class saleTicket2 {


    public static void main(String[] args) {
        //一份资源
        Ticket2 ticket = new Ticket2();
        //多个线程
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 80; i++) {
                ticket.sale();
            }
        }, "C").start();
    }



}

//资源类
class Ticket2 {
    //票数
    private int number = 100;

    //Lock锁
    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();//加锁
        try {
            if (number > 0)
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票,剩余" + number);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}

